<?php

namespace app\crontab\task;


use app\common\logic\NewsApi;
use think\Db;

/**
 * 众包费
 *
 * @icon fa fa-circle-o
 */
class NewsInsert extends Common
{
    public function __construct(array $params = [])
    {
        parent::__construct($params);
    }


    public function search() {
        if (config('site.start_catch') == 0) {
            echo '后台已经关闭抓取文章';
            return true;
        }
        $config = config('news_config');
        $tags = array_keys($config);
        $db = Db::name('self_news');
        //获取最新新闻
        foreach ($tags as $k => $v) {
            (new NewsApi($v))->apiData();
            //首先判断 之前插入的数据是否达到600条如果达到了600天那么久删除
            $count = $db->where(['tag' => $v])->count();

            if ($count > 1000) {

                $data = $db->where(['tag' => $v])->order('createtime', 'desc')->limit(1000)->select();
                $last = array_pop($data);
                $db->where(['tag' => $v])->where(['createtime'=>['lt', $last['createtime']]])->delete();
            }
        }

        sleep(2);
        return true;
    }


    public function delete() {
        Db::name('self_news')->chunk(1, function($news) {
            foreach ($news as $new) {
                $title = $new['title'];
                Db::name('self_news')->where([
                    'id' => ['neq', $new['id']],
                    'title' => $title
                ])->delete();
            }
        }, '', 'desc');
    }

}
